package com.ktg.mes.unit.model;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.mes.unit.sync1.Sync1ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class Model1ServiceImpl<M extends BaseMapper<T>, T> extends Sync1ServiceImpl<M, T> implements IModelService<T> {

    // spring注入ApplicationContext
    @Autowired
    private ApplicationContext context;

    /***
     *动态初始化Service
     * @return
     */
    @SuppressWarnings("unchecked")
    public  IService getService(String className) {
        try {
            Class clazz = Class.forName(className);
            // 逻辑处理你需要实例化的类
            String beanName =  clazz.getSimpleName();
            String firstLowerBeanName = beanName.substring(0,1).toLowerCase()+beanName.substring(1,beanName.length());
            Object obj = context.getBean(firstLowerBeanName, clazz);
            if (obj instanceof IService ){
                if (obj instanceof ServiceImpl){
                    return  (IService)obj;
                }else {
                    throw new RuntimeException(" className 需要继承 com.baomidou.mybatisplus.core.mapper.BaseMapper");
                }
            }else {
                throw new RuntimeException(" className 需要继承 com.baomidou.mybatisplus.extension.service.IService");
            }
        } catch (Exception e) {
            System.out.println("请传入正确的 className");
            e.printStackTrace();
        }
        return null;
    }


    public boolean save(Object object,String iServiceImpl_Name){
        if (object == null){
            return false;
        }
        IService one = (IService) getService(iServiceImpl_Name);
        if (one != null){
            return one.save(object);
        }
        return false;
    }


}
